package cn.machen.www.fashion.controller;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
import cn.machen.www.fashion.pojo.Cart;
import cn.machen.www.fashion.pojo.User;
import cn.machen.www.fashion.services.UserService;
import cn.machen.www.fashion.utils.BaseServlet;
import cn.machen.www.fashion.utils.Exception.UserException;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import jdk.nashorn.internal.ir.debug.JSONWriter;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.commons.beanutils.BeanUtils;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;

public class UserServlet extends BaseServlet{
    private UserService service = new UserService();


    /**用户登录
     *      封装表单数据到User对象中
     *      数据库输入校验（用户名，密码，激活状态）
     *          否：保留错误信息到相应到前端页面
     *          是：保存用户到session中，重定向到首页
     */
    public String login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("hello");
        User user = CommonUtils.toBean(request.getParameterMap(), User.class);
        try {
            User result = service.login(user);
            //用户登录成功将用户保存到session中，还用给用户绑定一个购物车
            request.getSession().setAttribute("user",user);
            request.getSession().setAttribute("cart",new Cart());
            //跳转到首页
           request.getRequestDispatcher("/main.jsp").forward(request,response);
        } catch (UserException e) {
            System.out.println(e.getMessage());
            request.setAttribute("errors",e.getMessage());
           return "f:/jsps/user/login.jsp";
        }
        return null;
    }
    /*用户退出：
           销毁session中的用户
           重定向到index.jsp中
    */
    public String quit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getSession().invalidate();
        request.getRequestDispatcher("/main.jsp").forward(request,response);
        return null;
    }

    /*邮箱激活*/
    public String active(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //得到激活码
        String code = request.getParameter("code");
        try {
            service.active(code);
        } catch (UserException e) {
            request.setAttribute("errors",e.getMessage());
            request.getRequestDispatcher("/regist.jsp").forward(request,response);
        }
        response.sendRedirect("/jsp/msg.jsp");
        return null;
    }
        /*用户注册*/
    public String regesit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("regesit");
             //封装表单数据到User对象中
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        user.setEmail(request.getParameter("email"));
        //为对象生成一个uid和激活码
        user.setUid(CommonUtils.uuid());
        user.setActivecode(CommonUtils.uuid()+CommonUtils.uuid());
        System.out.println(user.getUsername());
             //service层逻辑处理
        try {
            service.regesit(user);
        } catch (UserException e) {
            System.out.println(e.getMessage());
            response.getWriter().print(e.getMessage());
            return null;
        }
           //发送激活邮件
        Properties props = new Properties();
        props.load(this.getClass().getResourceAsStream("/email_template.properties"));
        String host = props.getProperty("host");//获取服务器主机
        String uname = props.getProperty("username");//获取用户名
        String pwd = props.getProperty("password");//获取密码
        String from = props.getProperty("from");//获取发件人
        String to = user.getEmail();//获取收件人
        String subject = props.getProperty("subject");//获取主题
        String content = props.getProperty("content");//获取邮件内容
        content = MessageFormat.format(content, user.getActivecode());//替换{0}

        Session session = MailUtils.createSession(host, uname, pwd);//得到session
        Mail mail = new Mail(from, to, subject, content);//创建邮件对象
        try {
            MailUtils.send(session, mail);//发邮件！
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        response.getWriter().print("注册成功，请前往邮箱激活");
        return null;
    }
}
